library image;

import 'dart:io';

import 'package:analyzer/dart/element/element.dart';
import 'package:build/src/builder/build_step.dart';
import 'package:source_gen/source_gen.dart';

///自动生成所有图片资源的索引，类似于android的R文件
class ImagePathParser {
  ///图片文件相对路径
  final String pathName;

  ///生成的索引类名
  final String resClassName;

  const ImagePathParser(this.pathName, [this.resClassName = "ImageRes"]);
}

class ImagePathGenerator extends GeneratorForAnnotation<ImagePathParser> {
  @override
  generateForAnnotatedElement(
      Element element, ConstantReader annotation, BuildStep buildStep) {
    var path = annotation.peek("pathName")!.stringValue;
    var className = annotation.peek("resClassName")!.stringValue;

    var imageRes = ""; //自动生成的资源索引
    var imageDir = Directory(path);
    imageDir
        .listSync()
        .where((item) => item.path.endsWith(".png"))
        .forEach((item) {
      var tempPath = item.path.replaceAll("\\", "/");
      var resName = tempPath.substring(
          tempPath.lastIndexOf("/") + 1, tempPath.lastIndexOf("."));
      imageRes = "$imageRes\nstatic const String $resName = \"$tempPath\";";
    });

    return """
    class $className{
      $imageRes
    }
    """;
  }
}
